package com.waypolice.manager.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.waypolice.common.constant.BorrowConstant;
import com.waypolice.common.utils.SpringContextUtil;
import com.waypolice.common.utils.StringUtil;
import com.waypolice.manager.service.BorAuditService;
import com.waypolice.manager.service.BorRegisterService;
import com.waypolice.manager.service.CmsSinItemService;
import com.waypolice.manager.service.VolAndItemService;
import com.waypolice.pojo.*;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.Expression;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 描述:
 *
 * @author zyp
 * @description 工作流流程结束监听器  处理后续流程内容
 * @create 2019-02-27 14:03
 */
public class ActivitiEndExectuionListener implements Serializable, ExecutionListener {

    private static final Logger logger = LoggerFactory.getLogger(ActivitiEndExectuionListener.class);

    private Expression message;

    private static ApplicationContext appCtx = SpringContextUtil.getApplicationContext();

    /**
     * 借阅登记表service
     */
    private static BorRegisterService borRegisterService = (BorRegisterService)appCtx.getBean(BorRegisterService.class);
    /**
     * 借阅审核表service
     */
    private static BorAuditService borAuditService = (BorAuditService)appCtx.getBean(BorAuditService.class);
    /**
     * 卷与件service
     */
    private static VolAndItemService volAndItemService = (VolAndItemService)appCtx.getBean(VolAndItemService.class);

    /**
     * 单件service
     */
    private static CmsSinItemService cmsSinItemService = (CmsSinItemService)appCtx.getBean(CmsSinItemService.class);

    @Autowired
    protected HistoryService historyService;

    @Autowired
    protected TaskService taskService;

    @Override
    public void notify(DelegateExecution execution) throws Exception {
        //登记id
        String borRegistId = execution.getProcessBusinessKey();
        String processInstanceId = execution.getProcessInstanceId();
        //获取借阅登记信息
        CmsBorRegister cmsBorRegister = borRegisterService.getRegistById(Long.parseLong(borRegistId));
        //获取最后一次审核的信息
        CmsBorAuditing cmsBorAuditing = borAuditService.getModifyAppliInfo(Long.parseLong(borRegistId));
        int taskType = cmsBorRegister.getTaskType();
        //如果当前审核为借阅
        switch(taskType){
            case BorrowConstant.AUDIT_TYPE_BORROW:
                //如果最后一次审核通过了
                if(cmsBorAuditing.getResultType()==BorrowConstant.AUDIT_RESULT_TRUE){
                    Long borType = cmsBorRegister.getBorType();
                    //如果为线上借阅，则将登陆的借阅状态改为已借阅
                    if (borType==BorrowConstant.BORROW_TYPE_UP) {
                        cmsBorRegister.setBorStatus(BorrowConstant.BORROW_STATUS_BOR);
                    }
                    cmsBorRegister.setExtend2(String.valueOf(BorrowConstant.AUDIT_RESULT_TRUE));
                    JSONObject jasonObject = new JSONObject();
                    jasonObject.put(processInstanceId,cmsBorRegister.getPlanReturnTime());
                    String returnDescription=JSON.toJSONString(jasonObject);
                    cmsBorRegister.setReturnDescription(returnDescription);
                    borRegisterService.updateByPrimaryKeySelective(cmsBorRegister);
                }else{
                    //如果最后一次审核失败（用户取消申请）了
                    //当为线下借阅时，此时的线下文档，应将已借阅状态修改为未借阅状态
                    Long borType = cmsBorRegister.getBorType();
                    if (borType==BorrowConstant.BORROW_TYPE_DOWN) {
                        List<CmsBorRegFile> cmsBorRegFiles = borRegisterService.selectBorRgtistById(Long.parseLong(borRegistId));
                        //防止修改卷次数过多问题
                        boolean isUpdateVolum = false;
                        for(CmsBorRegFile cmsBorRegFile : cmsBorRegFiles){
                            //获取文件形式  卷/件
                            String fileShape = cmsBorRegFile.getFileShape();
                            //如果是卷
                            if(String.valueOf(BorrowConstant.BORROW_FILE_VOLUM).equals(fileShape)){
                                CmsJudVolume cjv = new CmsJudVolume();
                                cjv.setVolId(cmsBorRegFile.getFileId());
                                cjv.setVolStatus(0);
                                //修改卷的状态
                                volAndItemService.updateByPrimaryKeySelectiveNoCheck(cjv);
                                //同时修改件的状态
                                volAndItemService.updateItemStatusByVoId(0,cmsBorRegFile.getFileId());
                            }else if(String.valueOf(BorrowConstant.BORROW_FILE_ITEM).equals(fileShape)){
                                CmsJudItem cmsJudItem = new CmsJudItem();
                                cmsJudItem.setItemId(cmsBorRegFile.getFileId());
                                cmsJudItem.setItemStatus(0L);
                                volAndItemService.updateItemByPrimaryKeySelective(cmsJudItem);
                                cmsJudItem = volAndItemService.selectByItemId(cmsBorRegFile.getFileId());
                                //判断当前借阅的件的数量与卷包含的数量是否一致
                                //当借阅的件的数量与卷包含的数量一致时，同时需要修改卷的状态
                                Long itmeVolId = cmsJudItem.getItmeVolId();
                                CmsJudVolume cmsJudVolume = volAndItemService.selectCmsJudVolumeByVolId(itmeVolId);
                                Long voId = cmsJudVolume.getVolId();
                                List<CmsJudItem> cmsJudItems = volAndItemService.selectAllByVolId(voId, 0);
                                //当借阅的件的数量与卷包含的数量一致时，同时需要修改卷的状态
                                if(cmsJudItems.size()==cmsBorRegFiles.size()&&!isUpdateVolum){
                                    cmsJudVolume.setVolStatus(2);
                                    volAndItemService.updateByPrimaryKeySelectiveNoCheck(cmsJudVolume);
                                    isUpdateVolum = true;
                                }
                                //如果是单件，则修改其文件状态
                            }else if(String.valueOf(BorrowConstant.BORROW_FILE_SIN_ITEM).equals(fileShape)){
                                CmsSinItem cmsSinItem = new CmsSinItem();
                                cmsSinItem.setItemId(cmsBorRegFile.getFileId());
                                cmsSinItem.setItemStatus(0L);
                                cmsSinItemService.updateSinItemByPrimaryKeySelective(cmsSinItem);
                            }
                        }
                    }
                }
                break;
            case BorrowConstant.AUDIT_TYPE_RENEW:
                if(cmsBorAuditing.getResultType()==BorrowConstant.AUDIT_RESULT_TRUE){
                    //将续借归还时间的值放入到预计归还时间中
                    Date newBorDate = cmsBorRegister.getRenewReturnTime();
                    long renewTimes = cmsBorRegister.getRenewTimes();
                    renewTimes++;
                    cmsBorRegister.setPlanReturnTime(newBorDate);
                    cmsBorRegister.setRenewTimes(renewTimes);
                    //同时将续借归还时间清空，作为辨别该登记是否在续借环节
                    cmsBorRegister.setRenewReturnTime(null);
                    cmsBorRegister.setRenewPurpose(null);
                    String returnDescription = cmsBorRegister.getReturnDescription();
                    if(StringUtils.isNotBlank(returnDescription)){
                        JSONObject jasonObject = JSONObject.parseObject(returnDescription);
                        jasonObject.put(processInstanceId,cmsBorRegister.getPlanReturnTime());
                        returnDescription=JSON.toJSONString(jasonObject);
                        cmsBorRegister.setReturnDescription(returnDescription);
                    }
                    borRegisterService.updateByPrimaryKey(cmsBorRegister);
                }else{
                    cmsBorRegister.setRenewReturnTime(null);
                    cmsBorRegister.setRenewPurpose(null);
                    borRegisterService.updateByPrimaryKey(cmsBorRegister);
                }
                break;
            case BorrowConstant.AUDIT_TYPE_SEARCH:
                //如果最后一次审核通过了,修改其审核状态
                if(cmsBorAuditing.getResultType()==BorrowConstant.AUDIT_RESULT_TRUE){
                    cmsBorRegister.setExtend2(String.valueOf(BorrowConstant.AUDIT_RESULT_TRUE));
                    borRegisterService.updateByPrimaryKeySelective(cmsBorRegister);
                }
                break;
            default:

        }
    }

    public Expression getMessage() {
        return message;
    }

    public void setMessage(Expression message) {
        this.message = message;
    }
}